<?php
class Admin_PicturesController extends Zend_Rest_Controller
{  
    const PATH = '/pics/';
	public function init(){
    	
    }

    public function indexAction(){
    	$list = array();
        $path = '.'.self::PATH;
        $url = self::PATH;
        $d = dir($path);
        while (false !== ($entry = $d->read())) {
            if (('.'==$entry) || ('..'==$entry))
                continue;
            $f = $path.$entry;
            $ext = pathinfo($f, PATHINFO_EXTENSION );
            if (($ext!='png') 
                && ($ext!='jpg')
                && ($ext!='gif')
                && ($ext!='jpeg')
               )
                continue;
            list($w,$h) = getimagesize($f);
            $list[] = array(
                'size'=>filesize($f),
                'name'=>$entry,
                'url'=>$url.$entry,
                'width'=>$w,
                'height'=>$h,
				'lastmod'	=>'2011-12-01'
            );
        }
        $d->close();
        $this->_helper->json(array('data'=>$list));
    }
    
	public function getAction(){
        $this->_helper->viewRenderer->setRender('editor-js');
		$this->_helper->layout()->disableLayout();
    }
    
	public function putAction(){
    
    }
    
    public function postAction()
    {
    	$form =new Admin_Form_PictureUpload(Admin_Model_GalleryItem::getTmpPath());
      	if (!$form->isValid($this->getRequest()->getParams())) {
            $this->_helper->json(array('success'=>false, 'msg'=> 'В полях формы заданы неверные значения'));
            //$this->_helper->layout()->disableLayout();
            //Нельзя заменять на $this->_helper->json($result);
            //почему???
            return;
        }
        $fi = $form->newfile->getFileInfo();
        if (!$form->newfile->receive()){
            $this->_helper->json(array('success'=>false, 'msg'=>'Невозможно получить файл'));
            return;
        }
        $location = $form->newfile->getFileName();
        $path = '.'.self::PATH;
        $ext = pathinfo($fi['newfile']['name'],PATHINFO_EXTENSION);
        $newname = time().'.'.$ext;
        $relpath = $path.$newname;
        rename($location,$relpath);
        list($w, $h) = getimagesize($relpath);
        
        $this->view->result = array('success'=>true, 
            'data'=>array(
                'size'=>filesize($relpath),
                'name'=>$newname,
                'url'=>self::PATH.$newname,
                'width'=>$w,
                'height'=>$h,
                'lastmod'	=>'2011-12-01'
            ));
      	$this->_helper->layout()->disableLayout();
        /* Нельзя заменять на $this->_helper->json($result);
         * потому что должно быть Content-Type: text/html
         * а в json там другое
         */
    }
    
	public function deleteAction(){
    
    }
}